﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using Fcdbas.Core.DataAccess;
using Fcdbas.Biz;
using Fcdbas.Core;
using Fcdbas.WinUI.Controls;
using Fcdbas.WinUI.Forms;
using Fcdbas.Platform.Properties;
using System.Xml;
using System.Reflection;
using Fcdbas.Core.Reflection;
using Fcdbas.Platform.Enums;

namespace Fcdbas.WinUI.Design
{
    public partial class DataSourceBindingPropertiesEdit : DevExpress.XtraEditors.XtraForm
    {
        private BaseForm _liveForm;
        private IContainer _liveContainer;
        private DataSourceBinding oldDataSource;
        private DataSourceBinding newDataSource;
        private List<DataItem> dataColumns;
        private List<Controls.cGridControl> _dataGridViews;
        private List<Control> _dataControls;
        private List<cLabel> Lables;
        private ISite _designSite;
        public DataSourceBindingPropertiesEdit(DataSourceBinding editDataSource)
        {
            InitializeComponent();
            tabCDataSourceBinding.SelectedTabPageIndex = 0;
            DataSourceBinding.UserDesignMode = true;
            oldDataSource = editDataSource;
            _designSite = editDataSource.Site;
            this.txtObjectName.Text = editDataSource.Name;
            dataColumns = new List<DataItem>();
            BindToUI(oldDataSource);
            Map(true);
            
            InitBind();
            FindBindingControl();
        }

        private void DataSourceBindingPropertiesEdit_Load(object sender, EventArgs e)
        {
            
        }
        private void GetEntityList(DevExpress.XtraEditors.Repository.RepositoryItemComboBox upComboBox)
        {
            ITypeDiscoveryService typeDiscovery = oldDataSource.Site.GetService(typeof(ITypeDiscoveryService)) as ITypeDiscoveryService;

            if (typeDiscovery != null)
            {
                Cursor previousCursor = Cursor.Current;
                Cursor.Current = Cursors.WaitCursor;

                try
                {
                    ICollection types = typeDiscovery.GetTypes(typeof(Fcdbas.Core.IEntity), false);
                    var sorted = from t in types.Cast<Type>()
                                 orderby t.Name
                                 select t;

                    foreach (Type type in sorted)
                    {
                        if (type.Assembly.FullName.Substring(0, type.Assembly.FullName.IndexOf(",")) != "Fcdbas.Core" &&
                          typeof(Fcdbas.Core.IEntity).IsAssignableFrom(type))
                            upComboBox.Items.Add(type.ToString());
                    }
                }
                finally
                {
                    Cursor.Current = previousCursor;
                }
            }
        }
        private void InitGridSelectItem()
        {
            foreach (GridColumn gc in this.gvColumns.Columns)
            {
                if (gc.FieldName.ToUpper() == "COLUMNNAME")
                    gc.Fixed = FixedStyle.Left;
                if (gc.FieldName.ToUpper() == "CAPTION")
                    gc.Fixed = FixedStyle.Left;
                if (gc.FieldName.ToUpper() == "UPDATEOPTION")
                {
                    DevExpress.XtraEditors.Repository.RepositoryItemComboBox upComboBox = new DevExpress.XtraEditors.Repository.RepositoryItemComboBox();
                    foreach (DataItemUpdate type in Enum.GetValues(typeof(DataItemUpdate)))
                    {
                        upComboBox.Items.Add(type);
                    }
                    gc.ColumnEdit = upComboBox;
                }
                if (gc.FieldName.ToUpper() == "FLAGS")
                {
                    DevExpress.XtraEditors.Repository.RepositoryItemComboBox upComboBox = new DevExpress.XtraEditors.Repository.RepositoryItemComboBox();
                    foreach (DataItemFlags type in Enum.GetValues(typeof(DataItemFlags)))
                    {
                        upComboBox.Items.Add(type);
                    }
                    gc.ColumnEdit = upComboBox;
                }
                if (gc.FieldName.ToUpper() == "FORMATOPTION")
                {
                    string[] m_Objects = { "Uppercase", "Lowercase", "Currency", "Percentage", "Decimal", "Integer", "Date", "DateTime", "Time", "Unformatted" };
                    DevExpress.XtraEditors.Repository.RepositoryItemComboBox upComboBox = new DevExpress.XtraEditors.Repository.RepositoryItemComboBox();
                    foreach (string type in m_Objects)
                    {
                        upComboBox.Items.Add(type);
                    }
                    gc.ColumnEdit = upComboBox;
                }
                if (gc.FieldName.ToUpper() == "LOGICALPARENT")
                {

                    DevExpress.XtraEditors.Repository.RepositoryItemComboBox upComboBox = new DevExpress.XtraEditors.Repository.RepositoryItemComboBox();
                    GetEntityList(upComboBox);
                    gc.ColumnEdit = upComboBox;
                }
            }
        }
        private void BindToUI(DataSourceBinding dsb)
        {
            txtLogicalUnit.Text = dsb.LogicalUnit;
            txtModuleName.Text = dsb.Module;
            txtObjectName.Text = dsb.Name;
            txtPackage.Text = dsb.PackageName;
            cboView.Text = dsb.ViewName;
            medOrderby.Text = dsb.DefaultOrderBy;
            medWhere.Text = dsb.DefaultWhere;
            chkEdit.Checked = dsb.AllowEdit;
            chkNew.Checked = dsb.AllowNew;
            chkRemove.Checked = dsb.AllowRemove;
            rgUpdates.SelectedIndex = (int)dsb.Updates;
        }
        private void UIToEntity(DataSourceBinding dsb)
        {
            dsb.LogicalUnit = txtLogicalUnit.Text;
            dsb.Module = txtModuleName.Text;
            //dsb.Name = txtObjectName.Text;
            dsb.PackageName = txtPackage.Text;
            dsb.ViewName = cboView.Text;
            dsb.DefaultOrderBy = medOrderby.Text;
            dsb.DefaultWhere=medWhere.Text;
            dsb.AllowEdit = chkEdit.Checked;
            dsb.AllowNew = chkNew.Checked;
            dsb.AllowRemove = chkRemove.Checked;
            dsb.Updates = (Fcdbas.Platform.Enums.UpdatesSql)rgUpdates.SelectedIndex;
             
            
        }
        private void FindBindingControl()
        {
            _dataControls = new List<Control>();
            _dataGridViews = new List<cGridControl>();
            Lables = new List<cLabel>();
            DataSourceBinding oldDataSourceBinding = oldDataSource as DataSourceBinding;
            _liveContainer = oldDataSourceBinding.Container;
            int componentCount = _liveContainer.Components.Count;
            
            _liveForm = oldDataSourceBinding.ParentForm;

            for (int i = 0; i < componentCount; i++)
            {
                IComponent component = oldDataSourceBinding.Container.Components[i];
                //if (component is DataSetBinding)
                //    _dataSetBinding = component as DataSetBinding;
                if (component is cLabel)
                    Lables.Add((cLabel)component);
                if (component is Controls.cGridControl)
                {
                    cGridControl dataGridView = (cGridControl)component;
                    if (dataGridView.DataSource != null && dataGridView.DataSource.Equals(oldDataSourceBinding) )
                        _dataGridViews.Add(dataGridView);
                    else if(oldDataSourceBinding.Name == "MasterdataSourceBinding")
                        _dataGridViews.Add(dataGridView);
                }
                else if (component is Control &&
                        ((Control)component).DataBindings.Count > 0)
                {
                    Control control = (Control)component;
                    if (control is IOwningDataSourceBinding &&
                        ((IOwningDataSourceBinding)control).OwningDataSourceBinding != null &&
                        ((IOwningDataSourceBinding)control).OwningDataSourceBinding.Equals(oldDataSourceBinding))
                        _dataControls.Add(control);
                }
                else if (component is BaseForm)
                {
                    _liveForm = component as BaseForm;
                }
            }
        }

        private Point[] GetLastLocation()
        {
            Point lLocation = new Point(10, 10); ;
            Point cLocation = new Point(12, 26); ;
            if (_liveForm == null)
                return new Point[] { lLocation, cLocation };

            foreach (Control control in _liveForm.Controls)
            {
                if (control.Location.X > lLocation.X && control.Location.Y > lLocation.Y )
                    lLocation = control.Location;
            }
            if (lLocation.X > 10)
            {
                lLocation.X += 286;
                lLocation.Y += 40;
            }
            lLocation.X = _liveForm.Width < lLocation.X + 286 ? 10 : lLocation.X  ;
            lLocation.Y = _liveForm.Width < lLocation.X + 286 ? 26 : lLocation.Y;
            cLocation.Y = _liveForm.Width < lLocation.X + 286 ? lLocation.Y + 16 : lLocation.Y + 16;
            cLocation.X = _liveForm.Width < lLocation.X + 286 ? 10 : lLocation.X ;

            return new Point[] { lLocation, cLocation };
        }
        /// <summary>
        /// 绑定，true代表新建
        /// </summary>
        /// <param name="newMap"></param>
        private void Map(bool newMap)
        {
            #region newMap = true
            if (newMap)
            {
                newDataSource = new DataSourceBinding
                {
                    Module = oldDataSource.Module,
                    DefaultOrderBy = oldDataSource.DefaultOrderBy,
                    DefaultWhere = oldDataSource.DefaultWhere,
                   // Name = oldDataSource.Name,
                    
                    LogicalUnit = oldDataSource.LogicalUnit,
                    PackageName = oldDataSource.PackageName,
                    Updates = oldDataSource.Updates,
                    ViewName = oldDataSource.ViewName,
                    AllowNew = oldDataSource.AllowNew,
                    AllowEdit = oldDataSource.AllowEdit,
                    AllowRemove = oldDataSource.AllowRemove,
                    Warnings = oldDataSource.Warnings
                };

                
                DataSourceBinding oldDataSourceBinding = oldDataSource as DataSourceBinding;
                if (oldDataSource == null || oldDataSourceBinding.Columns == null)
                    return;

                if (oldDataSourceBinding.Columns != null)
                {
                    foreach (DataItem oldDataItem in oldDataSourceBinding.Columns)
                    {
                        if (oldDataItem.ColumnName.ToLower() == "objid" ||
                            oldDataItem.ColumnName.ToLower() == "objversion" ||
                            oldDataItem.ColumnName.ToLower() == "objdeleted")
                            continue;

                        DataItem newDataItem = new DataItem
                        {
                            Caption = oldDataItem.Caption,
                            ColumnName = oldDataItem.ColumnName,
                            DataType = oldDataItem.DataType,
                            Name = oldDataItem.Name,
                            OldColumnName = oldDataItem.ColumnName,
                            OldName = oldDataItem.Name,
                            Length = oldDataItem.Length,
                            EnumMethod = oldDataItem.EnumMethod,
                            Flags = oldDataItem.Flags,
                            FormatOption = oldDataItem.FormatOption,
                            Insertable = oldDataItem.Insertable,
                            LogicalParent = oldDataItem.LogicalParent,
                            OnlyInWhereClause = oldDataItem.OnlyInWhereClause,
                            Queryable = oldDataItem.Queryable,
                            Reference = oldDataItem.Reference,
                            Required = oldDataItem.Required,
                            Simple = oldDataItem.Simple,
                            UpdateOption = oldDataItem.UpdateOption,
                            UseEditor = oldDataItem.UseEditor,
                            Validate = oldDataItem.Validate,
                            PropertyChanged = oldDataItem.PropertyChanged,
                            RefFunction = oldDataItem.RefFunction,
                            FunctionDefine = oldDataItem.FunctionDefine,
                            CustomerFormat = oldDataItem.CustomerFormat,
                            IsImage = oldDataItem.IsImage ,
                            IsRichEdit = oldDataItem.IsRichEdit,
                            IsAssist = oldDataItem.IsAssist
                        };

                        dataColumns.Add(newDataItem);
                    }
                }
            }
            #endregion
            #region newMap = false
            else
            {
                UIToEntity(newDataSource);
               

                oldDataSource.Module = newDataSource.Module;
                oldDataSource.DefaultOrderBy = newDataSource.DefaultOrderBy;
                oldDataSource.DefaultWhere = newDataSource.DefaultWhere;
                //oldDataSource.LogicalParent = cboLogicalParent.SelectedItem as IDataSource;
                oldDataSource.LogicalUnit = txtLogicalUnit.Text ;//.SelectedItem;
                oldDataSource.PackageName = newDataSource.PackageName;
                oldDataSource.Updates = newDataSource.Updates;
                oldDataSource.ViewName = newDataSource.ViewName;

                oldDataSource.AllowEdit = chkEdit.Checked;
                oldDataSource.AllowNew = chkNew.Checked;
                oldDataSource.AllowRemove = chkRemove.Checked;

                if (oldDataSource.Columns != null)
                {
                    
                    int lBaseX = 10;
                    int cBaseX = 12;

                    Point lLocation;
                    Point cLocation;
                    Point[] lastLocations = GetLastLocation();
                    lLocation = lastLocations[0];
                    cLocation = lastLocations[1];

                    foreach (DataItem dataItem in dataColumns)
                    {
                        foreach (cGridControl gc in _dataGridViews)
                            UpdateDataGridViewColumn(gc.MainView as GridView, dataItem);

                        DataItem oldDataItem = GetDataItem(dataItem.ColumnName);
                        #region Add new
                        if (oldDataItem == null)
                        {
                            DataItem newDataItem = new DataItem
                            {
                                Name = dataItem.Name,
                                ColumnName = dataItem.ColumnName,
                                DataType = dataItem.DataType,
                                Caption = dataItem.Caption,
                                Length = dataItem.Length,
                                EnumMethod = dataItem.EnumMethod,
                                Flags = dataItem.Flags,
                                FormatOption = dataItem.FormatOption,
                                Insertable = dataItem.Insertable,
                                LogicalParent = dataItem.LogicalParent,
                                OnlyInWhereClause = dataItem.OnlyInWhereClause,
                                Queryable = dataItem.Queryable,
                                Reference = dataItem.Reference,
                                Required = dataItem.Required,
                                Simple = dataItem.Simple,
                                UpdateOption = dataItem.UpdateOption,
                                UseEditor = dataItem.UseEditor,
                                Validate = dataItem.Validate,
                                PropertyChanged = dataItem.PropertyChanged,
                                RefFunction = dataItem.RefFunction,
                                FunctionDefine = dataItem.FunctionDefine,
                                CustomerFormat = dataItem.CustomerFormat,
                                IsImage = dataItem.IsImage ,
                                IsRichEdit = dataItem.IsRichEdit,
                                IsAssist = dataItem.IsAssist
                            };
                            DataItem di = oldDataSource.Columns.Find(p => p.ColumnName == newDataItem.ColumnName);
                            if (di != null)
                                oldDataSource.Columns.Remove(di);
                            oldDataSource.Columns.Add(newDataItem);
                           // _liveContainer.Add(newDataItem);

                            if (_liveForm != null &&
                                newDataItem.AddToForm)
                            {
                                if (_liveForm is cFormWindow
                                    || _liveForm is cMasterDetailWindow
                                    || _liveForm is cContainerTabFormWindow
                                    || _liveForm is cDialogWindow
                                    )
                                {
                                    if (!oldDataSource.IsTable)
                                    {
                                        try
                                        {
                                            CreateBindingControl(oldDataSource, newDataItem, lLocation, cLocation);

                                        }
                                        catch (Exception ex)
                                        {
                                            Fcdbas.Core.Log.XTrace.WriteException(ex);
                                            MessageBox.Show(ex.ToString());
                                        }
                                        lLocation.X = _liveForm.Width < cLocation.X + 286 ? lBaseX : lLocation.X + 146;
                                        lLocation.Y = _liveForm.Width < cLocation.X + 286 ? cLocation.Y + 26 : lLocation.Y;
                                        cLocation.Y = _liveForm.Width < cLocation.X + 286 ? lLocation.Y + 16 : cLocation.Y;
                                        cLocation.X = _liveForm.Width < cLocation.X + 286 ? cBaseX : cLocation.X + 146;
                                    }
                                    else
                                    {
                                        cGridControl dataGridView = CreateDataGridView(oldDataSource);
                                        //foreach (DataItem dataItem in dataColumns)
                                        UpdateDataGridViewColumn(dataGridView.MainView as GridView, newDataItem);
                                    }
                                }
                            }
                        }
                        #endregion 
                        #region edit 
                        else
                        {
                            oldDataItem.Name = dataItem.Name;
                            oldDataItem.ColumnName = dataItem.ColumnName;
                            oldDataItem.DataType = dataItem.DataType;
                            oldDataItem.Caption = dataItem.Caption;
                            oldDataItem.Length = dataItem.Length;
                            oldDataItem.EnumMethod = dataItem.EnumMethod;
                            oldDataItem.Flags = dataItem.Flags;
                            oldDataItem.FormatOption = dataItem.FormatOption;
                            oldDataItem.Insertable = dataItem.Insertable;
                            oldDataItem.LogicalParent = dataItem.LogicalParent;
                            oldDataItem.OnlyInWhereClause = dataItem.OnlyInWhereClause;
                            oldDataItem.Queryable = dataItem.Queryable;
                            oldDataItem.Reference = dataItem.Reference;
                            oldDataItem.Required = dataItem.Required;
                            oldDataItem.Simple = dataItem.Simple;
                            oldDataItem.UpdateOption = dataItem.UpdateOption;
                            oldDataItem.UseEditor = dataItem.UseEditor;
                            oldDataItem.Validate = dataItem.Validate;
                            oldDataItem.PropertyChanged = dataItem.PropertyChanged;
                            oldDataItem.RefFunction = dataItem.RefFunction;
                            oldDataItem.FunctionDefine = dataItem.FunctionDefine;
                            oldDataItem.CustomerFormat = dataItem.CustomerFormat;
                            oldDataItem.IsImage = dataItem.IsImage;
                            oldDataItem.IsRichEdit = dataItem.IsRichEdit;
                            oldDataItem.IsAssist = dataItem.IsAssist;
                          //  PropertyDescriptor statePrperty = TypeDescriptor.GetProperties(typeof(IComponentPropertyChanged))["PropertyChanged"];

                          //  IComponentChangeService componentChangeService = oldDataItem.Site.GetService(typeof(IComponentChangeService)) as IComponentChangeService;
                          //  componentChangeService.OnComponentChanging(oldDataItem, statePrperty);
                          //  componentChangeService.OnComponentChanged(oldDataItem, statePrperty, false, true);

                            foreach (Control control in _dataControls)
                            {
                                try
                                {
                                    UpdateBindingControl(control, oldDataSource, dataItem);
                                }
                                catch (Exception ex)
                                {
                                    Fcdbas.Core.Log.XTrace.WriteException(ex);
                                    MessageBox.Show(ex.ToString());
                                }
                            }
                            DataItem di = oldDataSource.Columns.Find(p => p.ColumnName == oldDataItem.ColumnName);
                            if (di != null)
                                oldDataSource.Columns.Remove(di);
                            oldDataSource.Columns.Add(oldDataItem);
                             //   UpdateControlBindings(control, oldDataSource, dataItem);
                        }
                        #endregion
                    }
                    if (_liveForm is cTableWindow)
                    {
                        cGridControl dataGridView = _dataGridViews.Count > 0 ? _dataGridViews[0] : null;

                        if (dataGridView == null)
                            dataGridView = CreateDataGridView(oldDataSource);
                        dataGridView.DataSource = oldDataSource;
                        //dataGridView.Dock = System.Windows.Forms.DockStyle.Fill;
                        //dataGridView.Location = new Point(0, 0);
                        foreach (DataItem dataItem in dataColumns)
                            UpdateDataGridViewColumn(dataGridView.MainView as GridView, dataItem);
                    }
                    //foreach (Control control in _dataControls)
                    //    RemoveControlBinding(control, dataColumns);
                    RemoveDataItem(oldDataSource.Columns, dataColumns);
                }
                else
                {
                   
                    int lBaseX = 10;
                    int cBaseX = 12;

                    Point lLocation = new Point(lBaseX, 10);
                    Point cLocation = new Point(cBaseX, 26);

                    if (_liveForm != null)
                    {
                        if (_liveForm is cFormWindow
                            || _liveForm is cMasterDetailWindow
                            || _liveForm is cContainerTabFormWindow
                            || _liveForm is cDialogWindow
                            )
                        {
                            if (!oldDataSource.IsTable)
                            {
                                foreach (DataItem dataItem in dataColumns)
                                {
                                    if (dataItem.AddToForm)
                                    {
                                        try
                                        {
                                            CreateBindingControl(oldDataSource, dataItem, lLocation, cLocation);
                                        }
                                        catch (Exception ex)
                                        {
                                            Fcdbas.Core.Log.XTrace.WriteException(ex);
                                            MessageBox.Show(ex.ToString());
                                        }
                                        lLocation.X = _liveForm.Width < cLocation.X + 286 ? lBaseX : lLocation.X + 146;
                                        lLocation.Y = _liveForm.Width < cLocation.X + 286 ? cLocation.Y + 26 : lLocation.Y;
                                        cLocation.Y = _liveForm.Width < cLocation.X + 286 ? lLocation.Y + 16 : cLocation.Y;
                                        cLocation.X = _liveForm.Width < cLocation.X + 286 ? cBaseX : cLocation.X + 146;
                                    }
                                }
                            }
                            else
                            {
                                cGridControl dataGridView = CreateDataGridView(oldDataSource);
                                foreach (DataItem dataItem in dataColumns)
                                    UpdateDataGridViewColumn(dataGridView.MainView as GridView, dataItem);
                            }
                        }
                        else if (_liveForm is cTableWindow)
                        {
                            cGridControl dataGridView = _dataGridViews.Count > 0 ? _dataGridViews[0] : null;

                            if (dataGridView == null)
                                dataGridView = CreateDataGridView(oldDataSource);
                           
                            dataGridView.Dock = System.Windows.Forms.DockStyle.Fill;
                            dataGridView.Location = new Point(0, 0);
                            foreach (DataItem dataItem in dataColumns)
                                UpdateDataGridViewColumn(dataGridView.MainView as GridView, dataItem);
                        }
                    }
                }
            }
            #endregion
            //this.bindingSource1.DataSource = this.dataColumns;
            this.gcColumns.DataSource = this.dataColumns;
            InitGridSelectItem();
        }
        private cLabel GetControlBindLable(Control ctrl)
        {
            if (ctrl is IOwningDataSourceBinding)
                return ((IOwningDataSourceBinding)ctrl).BindLabel;
            else
                return null;
        }
        private cLabel FindLableByName(string name)
        {
            foreach (cLabel lb in Lables)
            {
                if (lb.Name == name)
                    return lb;
            }
            return null;
        }
        private void AddDefaultColumn(List<DataItem> dataSource)
        {
            return;

            DataSourceBinding oldDataSourceBinding = oldDataSource as DataSourceBinding;

            DataItem objIDColumn = new DataItem()
            {
                Name = "objid",
                ColumnName = "objid",
                DataType = typeof(string),
                EnumMethod = "",
                Flags = Platform.Enums. DataItemFlags.Key,
                FormatOption = "",
                Insertable = false,
                LogicalParent = "",
                OnlyInWhereClause = false,
                Queryable = false,
                Reference = "",
                Required = false,
                IsAssist = false,
                Simple = false,
                UpdateOption = Platform.Enums.DataItemUpdate.NotAllowed,
                UseEditor = false,
                Validate = ""
            };

            DataItem objVersionColumn = new DataItem()
            {
                Name = "objversion",
                ColumnName = "objversion",
                DataType = typeof(string),
                EnumMethod = "",
                Flags = Platform.Enums.DataItemFlags.Key,
                FormatOption = "",
                Insertable = false,
                LogicalParent = "",
                OnlyInWhereClause = false,
                Queryable = false,
                Reference = "",
                Required = false,
                Simple = false,
                IsAssist = false,
                UpdateOption = Platform.Enums.DataItemUpdate.NotAllowed,
                UseEditor = false,
                Validate = ""
            };

            DataItem objDeletedColumn = new DataItem()
            {
                Name = "objdeleted",
                ColumnName = "objdeleted",
                DataType = typeof(bool),
                EnumMethod = "",
                Flags = Platform.Enums.DataItemFlags.Key,
                FormatOption = "",
                Insertable = false,
                LogicalParent = "",
                OnlyInWhereClause = false,
                Queryable = false,
                Reference = "",
                Required = false,
                Simple = false,
                UpdateOption = Platform.Enums.DataItemUpdate.NotAllowed,
                UseEditor = false,
                Validate = ""
            };
            if (dataSource.Find(p =>p.ColumnName == "objid") == null)
            {
                dataSource.Add(objIDColumn);
                //_liveContainer.Add(objIDColumn);
            }
            if (dataSource.Find(p => p.ColumnName =="objversion") == null)
            {
                dataSource.Add(objVersionColumn);
                //_liveContainer.Add(objVersionColumn);
            }
            if (dataSource.Find(p => p.ColumnName == "objdeleted") == null)
            {
                dataSource.Add(objDeletedColumn);
               // _liveContainer.Add(objDeletedColumn);
            }
        }
        /// <summary>
        /// 删除多余的字段
        /// </summary>
        /// <param name="dataSource">要删除的字段</param>
        /// <param name="dataItems"></param>
        private void RemoveDataItem(List<DataItem> dataSource, List<DataItem> dataItems)
        {
            for (int i = 0; i < dataSource.Count; i++)
            {
                if (dataItems.Find(p => p.ColumnName == dataSource[i].ColumnName) == null)
                {
                    dataSource.RemoveAt(i);
                    i--;
                }
            }
        }
        private void RemoveControlBinding(Control control, List<DataItem> dataItems)
        {
            int count = control.DataBindings.Count - 1;
            Binding removedBinding = null;
            bool noMatch = false;

            while (count >= 0)
            {
                noMatch = false;
                removedBinding = control.DataBindings[count];

                foreach (DataItem dataItem in this.dataColumns)
                {
                    if (dataItem.ColumnName.Equals(removedBinding.BindingMemberInfo.BindingMember))
                    {
                        noMatch = true;
                        break;
                    }
                }

                if (!noMatch)
                    control.DataBindings.Remove(removedBinding);

                count--;
            }
        }
        private string LuName
        {
            get { return oldDataSource.Module + "." + oldDataSource.LogicalUnit + "." + oldDataSource.ViewName; }
        }
        private DataItem GetDataItem( string name)
        {
            //return (from c in dataTable where c.ColumnName == name select c).FirstOrDefault();
            foreach (Control ctrl in _dataControls)
            {
                if (ctrl is IReference)
                {
                    if (((IReference)ctrl).DataColumn != null && ((IReference)ctrl).DataColumn.ColumnName == name)
                        return ((IReference)ctrl).DataColumn;
                }
            }
            return null;
        }
        private Controls.cGridControl CreateDataGridView(DataSourceBinding oldDataSourceBinding)
        {
            foreach (cGridControl gc in this._dataGridViews)
            {
                if (gc.DataSource.Equals(oldDataSourceBinding))
                    return gc;
               
            }
            cGridControl dataGridView = new cGridControl();
           
            dataGridView.Location = new System.Drawing.Point(10, 10);
           
            dataGridView.DataSource = oldDataSourceBinding;
           
            dataGridView.Size = new System.Drawing.Size(400, 200);

            _liveForm.Controls.Add(dataGridView);
            _liveContainer.Add(dataGridView);
            this._dataGridViews.Add(dataGridView);
            dataGridView.Site.Name = "dgv" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(oldDataSourceBinding.ViewName.Replace(" ", ""));
            return dataGridView;
        }
        private GridColumn GetViewColumn(GridView dataGridView, string dataPropertyName)
        {
            foreach (GridColumn viewColumn in dataGridView.Columns)
            {
                if (viewColumn.FieldName.Equals(dataPropertyName))
                    return viewColumn;
            }

            return null;
        }
        private void UpdateDataGridViewColumn(GridView dataGridView, DataItem dataItem)
        {
            if (dataGridView.DataSource != null && !dataGridView.DataSource.Equals(oldDataSource))
                return;
            if (!dataItem.AddToForm)
                return;
            GridColumn dataGridViewColumn = GetViewColumn(dataGridView, string.IsNullOrEmpty(dataItem.OldColumnName) ? dataItem.ColumnName : dataItem.OldColumnName);
            
            string colName = "";
           // string itemName = "";
            if (dataGridViewColumn == null)
            {
                dataGridViewColumn = new GridColumn();
                dataGridViewColumn.Tag = dataItem;
                dataGridViewColumn.Caption = dataItem.Caption;
                dataGridViewColumn.FieldName = dataItem.ColumnName;
              //  dataGridViewColumn.Name = oldDataSource.LogicalUnit + "gcc" + GetControlName(dataItem.ColumnName);
                if(dataItem.OnlyInWhereClause)
                    dataGridViewColumn.Visible = true;
                else
                    dataGridViewColumn.Visible = false;
                if (!string.IsNullOrEmpty(dataItem.EnumMethod))
                {
                    DevExpress.XtraEditors.Repository.RepositoryItemComboBox colItem = new DevExpress.XtraEditors.Repository.RepositoryItemComboBox();
                    //colItem.Name = oldDataSource.LogicalUnit + "_col" + GetControlName(dataItem.ColumnName); ;
                    dataGridViewColumn.ColumnEdit = colItem;
                    dataGridView.GridControl.RepositoryItems.Add(colItem);
                    colItem.Name = oldDataSource.Name + "_col" + GetControlName(dataItem.ColumnName,false);
                    colName = oldDataSource.Name + "_colc" + GetControlName(dataItem.ColumnName, false);
                }
                else if (dataItem.DataType == typeof(DateTime))
                {
                    DevExpress.XtraEditors.Repository.RepositoryItemDateEdit dateEdit = new DevExpress.XtraEditors.Repository.RepositoryItemDateEdit();
                    dateEdit.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                    dateEdit.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                    dateEdit.EditFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                    dateEdit.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                    dateEdit.Mask.EditMask = "yyyy-MM-dd HH:mm:ss";
                   
                    
                    dataGridViewColumn.ColumnEdit = dateEdit;
                    dataGridView.GridControl.RepositoryItems.Add(dateEdit);
                    dateEdit.Name = oldDataSource.Name + "_col" + GetControlName(dataItem.ColumnName, false);
                    colName = oldDataSource.Name + "_cold" + GetControlName(dataItem.ColumnName, false);
                }
                else if (dataItem.DataType == typeof(bool) || dataItem.Simple)

                {
                    DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit chkBox = new DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit();
                    chkBox.DisplayValueChecked = "True";
                    chkBox.DisplayValueGrayed = "Gray";
                    chkBox.DisplayValueUnchecked = "False";
                    chkBox.ValueChecked = "True";
                    chkBox.ValueGrayed = "Gray";
                    chkBox.ValueUnchecked = "False";
                   
                    dataGridViewColumn.ColumnEdit = chkBox;
                    dataGridView.GridControl.RepositoryItems.Add(chkBox);
                    chkBox.Name = oldDataSource.Name + "_col" + GetControlName(dataItem.ColumnName, false);
                    colName = oldDataSource.Name + "_colb" + GetControlName(dataItem.ColumnName, false);
                }
                else if (dataItem.DataType == typeof(decimal))
                {
                    DevExpress.XtraEditors.Repository.RepositoryItemTextEdit numEdit = new DevExpress.XtraEditors.Repository.RepositoryItemTextEdit();

                    numEdit.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
                    numEdit.Mask.EditMask = "f";
                    numEdit.Mask.UseMaskAsDisplayFormat = true;
                    
                    dataGridViewColumn.ColumnEdit = numEdit;
                    dataGridView.GridControl.RepositoryItems.Add(numEdit);
                    numEdit.Name = oldDataSource.Name + "_col" + GetControlName(dataItem.ColumnName, false);
                    colName = oldDataSource.Name + "_coln" + GetControlName(dataItem.ColumnName, false);
                }
                //else if (dataItem.DataType == typeof(byte[]) && dataItem.IsImage)
                else if ( dataItem.IsImage)
                {
                    cRepositoryItemImageEdit imageEdit = new cRepositoryItemImageEdit();
                    dataGridViewColumn.ColumnEdit = imageEdit;
                    
                    dataGridView.GridControl.RepositoryItems.Add(imageEdit);
                    imageEdit.Name = oldDataSource.Name + "_col" + GetControlName(dataItem.ColumnName, false);
                    colName = oldDataSource.Name + "_cols" + GetControlName(dataItem.ColumnName, false);
                }
                else if (dataItem.UseEditor)
                {
                    DevExpress.XtraEditors.Repository.RepositoryItemMemoExEdit memoEdit = new DevExpress.XtraEditors.Repository.RepositoryItemMemoExEdit();


                    dataGridViewColumn.ColumnEdit = memoEdit;
                    dataGridView.GridControl.RepositoryItems.Add(memoEdit);
                    memoEdit.Name = oldDataSource.Name + "_col" + GetControlName(dataItem.ColumnName, false);
                    colName = oldDataSource.Name + "_coln" + GetControlName(dataItem.ColumnName, false);
                }
                else
                {
                    DevExpress.XtraEditors.Repository.RepositoryItemTextEdit txtEdit = new DevExpress.XtraEditors.Repository.RepositoryItemTextEdit();

                    dataGridViewColumn.ColumnEdit = txtEdit;

                    dataGridView.GridControl.RepositoryItems.Add(txtEdit);
                    txtEdit.Name = oldDataSource.Name + "_col" + GetControlName(dataItem.ColumnName, false);
                    colName = oldDataSource.Name + "_cols" + GetControlName(dataItem.ColumnName, false);
                }

              //  dataGridViewColumn.FieldName = dataItem.ColumnName;
              //  dataGridViewColumn.Caption = dataItem.Caption;
                dataGridView.Columns.Add(dataGridViewColumn);
                dataGridViewColumn.Name = colName;
               
                //dataGridViewColumn.ColumnEditName = itemName;
                //dataGridView.Container.Add(dataGridViewColumn);
            }
            //else
            //{
            //    GridColumn oldViewColumn = dataGridViewColumn;
            //    bool changedType = false;
            //    if (dataItem.OnlyInWhereClause)
            //        dataGridViewColumn.Visible = true;
            //    else
            //        dataGridViewColumn.Visible = false;
            //    if (!string.IsNullOrEmpty(dataItem.EnumMethod))
            //    {
            //        if (dataGridViewColumn.ColumnEdit.GetType() != typeof(DevExpress.XtraEditors.Repository.RepositoryItemComboBox))
            //        {
            //            changedType = true;
            //            dataGridViewColumn.ColumnEdit = new DevExpress.XtraEditors.Repository.RepositoryItemComboBox();
            //            dataGridViewColumn.ColumnEdit.Name = "colc" + dataItem.ColumnName;
            //        }

            //        dataGridViewColumn.Name = "col" + dataItem.ColumnName;

            //    }
            //    else if (dataItem.DataType == typeof(DateTime))
            //    {
            //        if (dataGridViewColumn.ColumnEdit.GetType() != typeof(DevExpress.XtraEditors.Repository.RepositoryItemDateEdit))
            //        {
            //            changedType = true;
            //            dataGridViewColumn.ColumnEdit = new DevExpress.XtraEditors.Repository.RepositoryItemDateEdit();
            //            dataGridViewColumn.ColumnEdit.Name = "colc" + dataItem.ColumnName;
            //        }

            //        dataGridViewColumn.Name = "col" + dataItem.ColumnName;
            //    }
            //    else if (dataItem.DataType == typeof(bool) || dataItem.Simple)
            //    {
            //        if (dataGridViewColumn.ColumnEdit.GetType() != typeof(DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit))
            //        {
            //            changedType = true;
            //            DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit chkBox = new DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit();
            //            chkBox.DisplayValueChecked = "True";
            //            chkBox.DisplayValueGrayed = "Gray";
            //            chkBox.DisplayValueUnchecked = "False";
            //            chkBox.ValueChecked = "True";
            //            chkBox.ValueGrayed = "Gray";
            //            chkBox.ValueUnchecked = "False";
            //            dataGridViewColumn.ColumnEdit = chkBox;
            //            dataGridViewColumn.ColumnEdit.Name = "colc" + dataItem.ColumnName; ;
            //        }

            //        dataGridViewColumn.Name = "col" + dataItem.ColumnName;
            //    }
            //    else
            //    {
            //        if (dataGridViewColumn.ColumnEdit.GetType() != typeof(DevExpress.XtraEditors.Repository.RepositoryItemTextEdit))
            //        {
            //            changedType = true;
            //            dataGridViewColumn.ColumnEdit = new DevExpress.XtraEditors.Repository.RepositoryItemTextEdit();
            //            dataGridViewColumn.ColumnEdit.Name = "colc" + dataItem.ColumnName;
            //        }

            //        dataGridViewColumn.Name = "col" + dataItem.ColumnName;
            //    }

            //    dataGridViewColumn.FieldName = dataItem.ColumnName;
            //    dataGridViewColumn.Caption = dataItem.Caption;

            //    if (changedType)
            //    {
            //        //dataGridViewColumn.AutoSizeMode = oldViewColumn.AutoSizeMode;
            //        //dataGridViewColumn.ContextMenuStrip = oldViewColumn.ContextMenuStrip;
            //        //dataGridViewColumn.DefaultCellStyle = oldViewColumn.DefaultCellStyle;
            //        //dataGridViewColumn.DefaultHeaderCellType = oldViewColumn.DefaultHeaderCellType;
            //        //dataGridViewColumn.DisplayIndex = oldViewColumn.DisplayIndex;
            //       // dataGridViewColumn.DividerWidth = oldViewColumn.DividerWidth;
            //       // dataGridViewColumn.FillWeight = oldViewColumn.FillWeight;
            //      //  dataGridViewColumn.Frozen = oldViewColumn.Frozen;
            //       // dataGridViewColumn.HeaderCell = oldViewColumn.HeaderCell;
            //       // dataGridViewColumn.MinimumWidth = oldViewColumn.MinimumWidth;
            //       // dataGridViewColumn.ReadOnly = oldViewColumn.ReadOnly;
            //       // dataGridViewColumn.Resizable = oldViewColumn.Resizable;
            //       // dataGridViewColumn.Selected = oldViewColumn.Selected;
            //        dataGridViewColumn.SortMode = oldViewColumn.SortMode;
            //       // dataGridViewColumn.ToolTipText = oldViewColumn.ToolTipText;
            //        dataGridViewColumn.Tag = oldViewColumn.Tag;
            //        dataGridViewColumn.Visible = oldViewColumn.Visible;
            //        //dataGridViewColumn.ValueType = oldViewColumn.ValueType;
            //        dataGridViewColumn.Width = oldViewColumn.Width;

            //        dataGridView.Columns.Remove(oldViewColumn);
            //        _liveContainer.Remove(oldViewColumn);
            //        oldViewColumn = null;

            //        dataGridView.Columns.Add(dataGridViewColumn);
            //        _liveContainer.Add(dataGridViewColumn);
            //    }
            //}
        }
        private object GetTypeByName(string luName)
        {
            ITypeDiscoveryService typeDiscovery = _designSite.GetService(typeof(ITypeDiscoveryService)) as ITypeDiscoveryService;
            ITypeResolutionService resolution = (ITypeResolutionService)_designSite.GetService(typeof(ITypeResolutionService));
            Type t= resolution.GetType(luName, false, true);
            if(t == null)
                XtraMessageBox.Show("没有找到实体单元: " + luName +"，详细请检查");
          //  return t;
            object obj = Activator.CreateInstance(t);
            return obj;
            //if (typeDiscovery != null)
            //{
            //    Cursor previousCursor = Cursor.Current;
            //    Cursor.Current = Cursors.WaitCursor;

            //    try
            //    {
            //        System.Collections.ICollection types = typeDiscovery.GetTypes(typeof(object), false);
            //        var sorted = from t in types.Cast<Type>()
            //                     where typeof(Fcdbas.Core.IEntity).IsAssignableFrom(t) orderby t.Name 
            //                     select t;

            //        foreach (Type type in sorted)
            //        {
            //            if (type.FullName == luName)
            //                return type;
            //            //if (type.Assembly.FullName.Substring(0, type.Assembly.FullName.IndexOf(",")) != "Fcdbas.DevLib" &&
            //            //  typeof(FunctionClassBase).IsAssignableFrom(type))
            //            //    cboFuncObject.Items.Add(type);
            //        }
            //    }
            //    finally
            //    {
            //        Cursor.Current = previousCursor;
            //    }
            //}
            //return null;
        }
        private void InitBind()
        {
            txtLogicalUnit.Text = oldDataSource.LogicalUnit;
            txtModuleName.Text = oldDataSource.Module;
            txtPackage.Text = oldDataSource.PackageName;
            cboView.EditValue = oldDataSource.ViewName;
            if (oldDataSource.Updates == Platform.Enums.UpdatesSql.Standard)
                rgUpdates.Properties.Items[0].Value = true;
            else
                rgUpdates.Properties.Items[0].Value = false;
            chkEdit.Checked = oldDataSource.AllowEdit;
            chkNew.Checked = oldDataSource.AllowNew;
            chkRemove.Checked = oldDataSource.AllowRemove;
            medOrderby.Text = oldDataSource.DefaultOrderBy;
            medWhere.Text = oldDataSource.DefaultWhere;
            if (TableColumns == null)
                TableColumns = new List<DataItem>();
            foreach (DataItem di in oldDataSource.Columns)
                this.TableColumns.Add(di);
            this.gcColumns.DataSource = this.dataColumns;
            InitGridSelectItem();
        }
        private bool FindControl(string name)
        {
            if (_liveForm == null || _liveForm.Controls.Count == 0)
                return false;
            foreach (Control ctrl in _liveForm.Controls)
            {
                if (ctrl.Name.ToUpper() == name.ToUpper())
                    return true;
            }
            return false;
        }
        private void CreateBindingControl(DataSourceBinding oldDataSourceBinding, DataItem dataItem, Point lLocation, Point cLocation)
        {
            
            cLabel clBindingLabel =null;
            string ctrlName = null;
            if (!(dataItem.DataType == typeof(bool) || dataItem.Simple))
            {
                cLabel lb = FindLableByName("lb"+Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName));
                if (lb != null)
                    clBindingLabel = lb;
                else
                {
                    clBindingLabel = new cLabel();
                    clBindingLabel.AutoSize = true;
                    //  clBindingLabel.DataBindings.Add(new System.Windows.Forms.Binding("DataItem", oldDataSourceBinding, dataItem.ColumnName, true));
                    //clBindingLabel.DataItem = dataItem.ColumnName;
                    clBindingLabel.Location = lLocation;
                    clBindingLabel.Text = string.IsNullOrEmpty(dataItem.Caption) ? dataItem.ColumnName : dataItem.Caption;
                    clBindingLabel.DataItem = dataItem.ColumnName;

                    _liveForm.Controls.Add(clBindingLabel);
                    _liveContainer.Add(clBindingLabel);
                    clBindingLabel.BringToFront();
                    ctrlName = "lb" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                    if (FindControl(ctrlName))
                        ctrlName = ctrlName + "1";
                    clBindingLabel.Site.Name = ctrlName;
                }
            }
            if (dataItem.DataType == typeof(string) && dataItem.UseEditor)
            {
                cMemoEdit memoEdit = new cMemoEdit();
                _liveForm.Controls.Add(memoEdit);
                _liveContainer.Add(memoEdit);
                memoEdit.BindLabel = clBindingLabel;
                memoEdit.DataColumn = dataItem;// new DataItem(dataItem.ColumnName, dataItem.DataType, dataItem.Length, dataItem.LogicalParent, dataItem.Simple, dataItem.UseEditor, dataItem.Queryable, dataItem.OnlyInWhereClause, dataItem.Validate, dataItem.Reference, dataItem.EnumMethod, dataItem.Caption, dataItem.FormatOption, dataItem.Required, dataItem.Insertable, dataItem.Flags, dataItem.UpdateOption);
                memoEdit.DataBindings.Clear();
                memoEdit.DataBindings.Add(new System.Windows.Forms.Binding("Text", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                memoEdit.DataColumn = dataItem;
                memoEdit.Location = cLocation;
                memoEdit.Column = dataItem.ColumnName;
                
                memoEdit.BringToFront();
                //memoEdit.Size = new System.Drawing.Size(262, 96);
                ctrlName = "meds" + GetControlName(dataItem.ColumnName);//Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                if (FindControl(ctrlName))
                    ctrlName = ctrlName + "1";
                memoEdit.Site.Name = ctrlName;
            }
            else if (dataItem.DataType == typeof(bool) || dataItem.Simple)
            {

                cCheckBox chkBindingControl = new cCheckBox();
                _liveForm.Controls.Add(chkBindingControl);
                _liveContainer.Add(chkBindingControl);
               // chkBindingControl.BindLabel = clBindingLabel;
                chkBindingControl.Column = dataItem.ColumnName;
                chkBindingControl.DataColumn = dataItem;// new DataItem(dataItem.ColumnName, dataItem.DataType, dataItem.Length, dataItem.LogicalParent, dataItem.Simple, dataItem.UseEditor, dataItem.Queryable, dataItem.OnlyInWhereClause, dataItem.Validate, dataItem.Reference, dataItem.EnumMethod, dataItem.Caption, dataItem.FormatOption, dataItem.Required, dataItem.Insertable, dataItem.Flags, dataItem.UpdateOption);
                chkBindingControl.AutoSize = true;
                chkBindingControl.DataBindings.Add(new System.Windows.Forms.Binding("EditValue", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                chkBindingControl.Location = cLocation;
                chkBindingControl.Text = string.IsNullOrEmpty(dataItem.Caption) ? dataItem.ColumnName : dataItem.Caption;
                chkBindingControl.Properties.DisplayValueChecked = "True";
                chkBindingControl.Properties.DisplayValueGrayed = "Gray";
                chkBindingControl.Properties.DisplayValueUnchecked = "False";
                chkBindingControl.Properties.ValueChecked = "True";
                chkBindingControl.Properties.ValueGrayed = "Gray";
                chkBindingControl.Properties.ValueUnchecked = "False";
                chkBindingControl.BringToFront();
                ctrlName = "chk" + GetControlName(dataItem.ColumnName);//Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                if (FindControl(ctrlName))
                    ctrlName = ctrlName + "1";
                chkBindingControl.Site.Name = ctrlName;
                return;
            }
            else if (dataItem.DataType == typeof(DateTime))
            {
                if (dataItem.FormatOption.ToUpper() != "TIME")
                {
                    cDateEdit dateTimeBindingControl = new cDateEdit();
                    _liveForm.Controls.Add(dateTimeBindingControl);
                    _liveContainer.Add(dateTimeBindingControl);
                    dateTimeBindingControl.BindLabel = clBindingLabel;
                    dateTimeBindingControl.Column = dataItem.ColumnName;
                    dateTimeBindingControl.DataColumn = dataItem;//new DataItem(dataItem.ColumnName, dataItem.DataType, dataItem.Length, dataItem.LogicalParent, dataItem.Simple, dataItem.UseEditor, dataItem.Queryable, dataItem.OnlyInWhereClause, dataItem.Validate, dataItem.Reference, dataItem.EnumMethod, dataItem.Caption, dataItem.FormatOption, dataItem.Required, dataItem.Insertable, dataItem.Flags, dataItem.UpdateOption);
                    dateTimeBindingControl.Location = cLocation;
                    dateTimeBindingControl.DataBindings.Add(new Binding("EditValue", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                    dateTimeBindingControl.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
                    new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
                    if (dataItem.FormatOption.ToUpper() == "DATETIME")
                    {
                        dateTimeBindingControl.Properties.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                        dateTimeBindingControl.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                        dateTimeBindingControl.Properties.EditFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                        dateTimeBindingControl.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                        dateTimeBindingControl.Properties.Mask.EditMask = "yyyy-MM-dd HH:mm:ss";
                    }
                    else
                    {
                        dateTimeBindingControl.Properties.DisplayFormat.FormatString = "yyyy-MM-dd";
                        dateTimeBindingControl.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                        dateTimeBindingControl.Properties.EditFormat.FormatString = "yyyy-MM-dd";
                        dateTimeBindingControl.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                        dateTimeBindingControl.Properties.Mask.EditMask = "yyyy-MM-dd";
                    }
                    dateTimeBindingControl.Properties.VistaTimeProperties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
            new DevExpress.XtraEditors.Controls.EditorButton()});
                    // dateTimeBindingControl.Format = System.Windows.Forms.DateTimePickerFormat.Short;
                    dateTimeBindingControl.Size = new System.Drawing.Size(140, 21);

                    dateTimeBindingControl.BringToFront();
                    ctrlName = "dt" + GetControlName(dataItem.ColumnName);//Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                    if (FindControl(ctrlName))
                        ctrlName = ctrlName + "1";
                    dateTimeBindingControl.Site.Name = ctrlName;
                }
                else
                {
                    cTimeEdit dateTimeBindingControl = new cTimeEdit();
                    _liveForm.Controls.Add(dateTimeBindingControl);
                    _liveContainer.Add(dateTimeBindingControl);
                    dateTimeBindingControl.BindLabel = clBindingLabel;
                    dateTimeBindingControl.Column = dataItem.ColumnName;
                    dateTimeBindingControl.DataColumn = dataItem;//new DataItem(dataItem.ColumnName, dataItem.DataType, dataItem.Length, dataItem.LogicalParent, dataItem.Simple, dataItem.UseEditor, dataItem.Queryable, dataItem.OnlyInWhereClause, dataItem.Validate, dataItem.Reference, dataItem.EnumMethod, dataItem.Caption, dataItem.FormatOption, dataItem.Required, dataItem.Insertable, dataItem.Flags, dataItem.UpdateOption);
                    dateTimeBindingControl.Location = cLocation;
                    dateTimeBindingControl.DataBindings.Add(new Binding("EditValue", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                    dateTimeBindingControl.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
            new DevExpress.XtraEditors.Controls.EditorButton()});
                    
                    // dateTimeBindingControl.Format = System.Windows.Forms.DateTimePickerFormat.Short;
                    dateTimeBindingControl.Size = new System.Drawing.Size(140, 21);

                    dateTimeBindingControl.BringToFront();
                    ctrlName = "dt" + GetControlName(dataItem.ColumnName);//Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                    if (FindControl(ctrlName))
                        ctrlName = ctrlName + "1";
                    dateTimeBindingControl.Site.Name = ctrlName;
                }
            }
           // else if (dataItem.DataType == typeof(byte[]) && dataItem.IsImage)
            else if ( dataItem.IsImage)
            {
                cPictureEdit picBindingControl = new cPictureEdit();
                _liveForm.Controls.Add(picBindingControl);
                _liveContainer.Add(picBindingControl);
                picBindingControl.BindLabel = clBindingLabel;
                picBindingControl.Properties.SizeMode = PictureSizeMode.Clip;
                picBindingControl.Properties.ShowMenu = true;
                picBindingControl.Properties.ShowScrollBars = true;
                picBindingControl.Properties.ShowZoomSubMenu = DevExpress.Utils.DefaultBoolean.True;
                picBindingControl.Column = dataItem.ColumnName;
                picBindingControl.DataColumn = dataItem;
                picBindingControl.DataBindings.Clear();
                picBindingControl.DataBindings.Add(new System.Windows.Forms.Binding("EditValue", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                picBindingControl.Location = cLocation;
                picBindingControl.Size = new System.Drawing.Size(140, 140);
                picBindingControl.Site.Name = "pic" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                picBindingControl.BringToFront();
            }
            else if (dataItem.IsRichEdit)
            {
                cRichEdit blobEdit = new cRichEdit();
                _liveForm.Controls.Add(blobEdit);

                _liveContainer.Add(blobEdit);
                blobEdit.ActiveViewType = DevExpress.XtraRichEdit.RichEditViewType.Simple;
                blobEdit.BindLabel = clBindingLabel;
                blobEdit.Column = dataItem.ColumnName;
                blobEdit.DataColumn = dataItem;
                blobEdit.DataBindings.Clear();
                blobEdit.DataBindings.Add(new System.Windows.Forms.Binding("OpenDocumentBytes", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                //  blobEdit.DataBindings.Add(new System.Windows.Forms.Binding("Text", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                blobEdit.Location = cLocation;
                blobEdit.Size = new System.Drawing.Size(140, 200);
                blobEdit.Site.Name = "rich" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                blobEdit.BringToFront();
            }
            else if (dataItem.IsBlobEdit)
            {
                cBlobEdit blobEdit = new cBlobEdit();
                _liveForm.Controls.Add(blobEdit);

                _liveContainer.Add(blobEdit);
                
                blobEdit.BindLabel = clBindingLabel;
                blobEdit.Column = dataItem.ColumnName;
                blobEdit.DataColumn = dataItem;
                blobEdit.DataBindings.Clear();
                blobEdit.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
                    new DevExpress.XtraEditors.Controls.EditorButton()});
                blobEdit.DataBindings.Add(new System.Windows.Forms.Binding("Text", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                blobEdit.Location = cLocation;
                blobEdit.Size = new System.Drawing.Size(140, 24);
                blobEdit.Site.Name = "blob" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                blobEdit.BringToFront();
            }
            else
            {
                Control nameControl = null;
                if (dataItem.Flags == Platform.Enums.DataItemFlags.Key && dataItem.PropertyChanged == true)
                {
                    cRecSelComboBox rsBindingControl = new cRecSelComboBox();
                    _liveForm.Controls.Add(rsBindingControl);
                    _liveContainer.Add(rsBindingControl);
                    foreach (DataItem di in TableColumns)
                    {
                        if (di.Queryable)
                        {
                            rsBindingControl.AddColumn(dataItem);
                        }
                    }
                    rsBindingControl.DataSource = oldDataSourceBinding;
                    rsBindingControl.BindLabel = clBindingLabel;
                    rsBindingControl.Column = dataItem.ColumnName;
                    rsBindingControl.DataColumn = dataItem;//new DataItem(dataItem.ColumnName, dataItem.DataType, dataItem.Length, dataItem.LogicalParent, dataItem.Simple, dataItem.UseEditor, dataItem.Queryable, dataItem.OnlyInWhereClause, dataItem.Validate, dataItem.Reference, dataItem.EnumMethod, dataItem.Caption, dataItem.FormatOption, dataItem.Required, dataItem.Insertable, dataItem.Flags, dataItem.UpdateOption);
                    rsBindingControl.DataBindings.Clear();
                    rsBindingControl.DataBindings.Add(new Binding("EditValue", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                    //rsBindingControl.DataBindings.Add(new Binding("EditValue", oldDataSourceBinding, "objid", true, DataSourceUpdateMode.OnPropertyChanged));

                    rsBindingControl.DisplayMember = dataItem.ColumnName;
                    rsBindingControl.ValueMember = dataItem.ColumnName;
                    rsBindingControl.Location = cLocation;
                    //rsBindingControl.Size = new System.Drawing.Size(140, 21);
                    ctrlName = "scb" + GetControlName(dataItem.ColumnName);//Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                    if (FindControl(ctrlName))
                        ctrlName = ctrlName + "1";
                    rsBindingControl.Site.Name = ctrlName;
                    rsBindingControl.BringToFront();
                    nameControl = rsBindingControl;
                }
                else if (!string.IsNullOrEmpty(dataItem.EnumMethod))
                {
                    cComboBox cboBindingControl = new cComboBox();
                    _liveForm.Controls.Add(cboBindingControl);
                    _liveContainer.Add(cboBindingControl);
                    cboBindingControl.Column = dataItem.ColumnName;
                    cboBindingControl.DataColumn = dataItem;
                    cboBindingControl.DataBindings.Add(new System.Windows.Forms.Binding("Text", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                    cboBindingControl.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
                    cboBindingControl.Properties.AutoComplete = true;
                    cboBindingControl.Location = cLocation;
                    cboBindingControl.Size = new System.Drawing.Size(140, 20);
                    cboBindingControl.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
            new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
                    ctrlName = "cbo" + GetControlName(dataItem.ColumnName);//Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                    if (FindControl(ctrlName))
                        ctrlName = ctrlName + "1";
                    cboBindingControl.Site.Name = ctrlName;
                    cboBindingControl.BringToFront();
                    nameControl = cboBindingControl;
                }
                else
                {
                    cTextEdit txtBindingControl = new cTextEdit();
                    _liveForm.Controls.Add(txtBindingControl);
                    if (!dataItem.Required)
                        txtBindingControl.Properties.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
                    _liveContainer.Add(txtBindingControl);
                    txtBindingControl.BindLabel = clBindingLabel;
                    txtBindingControl.Column = dataItem.ColumnName;
                    txtBindingControl.DataColumn = dataItem;
                    txtBindingControl.DataBindings.Clear();
                    txtBindingControl.DataBindings.Add(new System.Windows.Forms.Binding("Text", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                    txtBindingControl.Location = cLocation;
                    txtBindingControl.Size = new System.Drawing.Size(140, 21);
                    txtBindingControl.Site.Name = "txt" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                    txtBindingControl.BringToFront();
                    nameControl = txtBindingControl;
                }

                if (dataItem.DataType == typeof(byte) ||
                    dataItem.DataType == typeof(byte[]) ||
                    dataItem.DataType == typeof(char) ||
                    dataItem.DataType == typeof(Guid) ||
                    dataItem.DataType == typeof(object) ||
                    dataItem.DataType == typeof(sbyte) ||
                    dataItem.DataType == typeof(string) ||
                    dataItem.DataType == typeof(TimeSpan))
                    if (nameControl is cTextEdit)
                        nameControl.Site.Name = "txts" + GetControlName(dataItem.ColumnName);//Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                    else
                        if (dataItem.DataType == typeof(decimal) ||
                        dataItem.DataType == typeof(double) ||
                        dataItem.DataType == typeof(Int16) ||
                        dataItem.DataType == typeof(int) ||
                        dataItem.DataType == typeof(Int64) ||
                        dataItem.DataType == typeof(Single) ||
                        dataItem.DataType == typeof(UInt16) ||
                        dataItem.DataType == typeof(uint) ||
                        dataItem.DataType == typeof(UInt64))
                        {
                            //nameControl.Site.Name = "dfn" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                            if (nameControl is cTextEdit)
                            {
                                nameControl.Site.Name = "txtn" + GetControlName(dataItem.ColumnName);//Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                                ((cTextEdit)nameControl).Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
                            }
                        }
            }

           
        }
        private void UpdateControlBindings(Control control, DataSourceBinding dataSource, DataItem dataItem)
        {
            Binding binding = GetBinding(control, dataSource, dataItem.OldColumnName);
            if (binding != null)
            {
                if (!binding.BindingMemberInfo.BindingMember.Equals(dataItem.ColumnName))
                {
                    control.DataBindings.Remove(binding);
                    control.DataBindings.Add(new Binding(binding.PropertyName, dataSource, dataItem.ColumnName, true));
                }
            }
            if (control is IReference)
            {
                ((IReference)control).DataColumn = dataItem;
                
            }
        }
        private Binding GetBinding(Control control, DataSourceBinding dataSource, string dataPropertyName)
        {
            foreach (Binding binding in control.DataBindings)
            {
                if (binding.DataSource.Equals(dataSource))
                {
                    if (binding.BindingMemberInfo.BindingMember.Equals(dataPropertyName))
                        return binding;
                }
            }

            return null;
        }
        private void UpdateBindingControl(Control control, DataSourceBinding oldDataSourceBinding, DataItem dataItem)
        {
            if (control is IReference)
            {
                if (((IReference)control).DataColumn.ColumnName != dataItem.ColumnName)
                    return;

            }

            UpdateControlBindings(control, oldDataSourceBinding, dataItem);

            if (control is cLabel)
            {
                control.Text = string.IsNullOrEmpty(dataItem.Caption) ? dataItem.Caption : dataItem.ColumnName;
                control.Site.Name = "cl" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                return;
            }
            if (dataItem.DataType == typeof(string) && dataItem.UseEditor)
            {
                if(!(control is cMemoEdit))
                {
                    _liveForm.Controls.Remove(control);
                    _liveContainer.Remove(control);
                    cMemoEdit memoEdit = new cMemoEdit();
                    _liveForm.Controls.Add(memoEdit);
                    _liveContainer.Add(memoEdit);
                   
                    memoEdit.BindLabel = GetControlBindLable(control);
                    memoEdit.DataColumn = dataItem;// new DataItem(dataItem.ColumnName, dataItem.DataType, dataItem.Length, dataItem.LogicalParent, dataItem.Simple, dataItem.UseEditor, dataItem.Queryable, dataItem.OnlyInWhereClause, dataItem.Validate, dataItem.Reference, dataItem.EnumMethod, dataItem.Caption, dataItem.FormatOption, dataItem.Required, dataItem.Insertable, dataItem.Flags, dataItem.UpdateOption);
                    memoEdit.DataBindings.Clear();
                    memoEdit.DataBindings.Add(new System.Windows.Forms.Binding("Text", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                    memoEdit.DataColumn = dataItem;
                    memoEdit.Location = control.Location;
                
                    //memoEdit.Size = new System.Drawing.Size(262, 96);
                    memoEdit.Site.Name = "med" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                }
                else{
                    ((cMemoEdit)(control)).DataColumn = dataItem;
                }
            }
            else if (dataItem.DataType == typeof(bool) || dataItem.Simple)
            {
                if (!(control is cCheckBox))
                {
                    _liveForm.Controls.Remove(control);
                    _liveContainer.Remove(control);
                    cCheckBox chkBindingControl = new cCheckBox();
                    _liveForm.Controls.Add(chkBindingControl);
                    _liveContainer.Add(chkBindingControl);
                    chkBindingControl.DataColumn = dataItem;
                    chkBindingControl.BindLabel = GetControlBindLable(control);
                    chkBindingControl.AutoSize = true;
                    chkBindingControl.Text = string.IsNullOrEmpty(dataItem.Caption) ? dataItem.ColumnName : dataItem.Caption;
                    chkBindingControl.Properties.DisplayValueChecked = "True";
                    chkBindingControl.Properties.DisplayValueGrayed = "Gray";
                    chkBindingControl.Properties.DisplayValueUnchecked = "False";
                    chkBindingControl.Properties.ValueChecked = "True";
                    chkBindingControl.Properties.ValueGrayed = "Gray";
                    chkBindingControl.Properties.ValueUnchecked = "False";
                    chkBindingControl.DataBindings.Add(new System.Windows.Forms.Binding("Checked", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                    chkBindingControl.Location = control.Location;
                    
                    chkBindingControl.Site.Name = "chk" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                    return;
                }
                else{
                     cCheckBox chkBindingControl = control as cCheckBox;
                     chkBindingControl.DataColumn = dataItem;
                        chkBindingControl.Text = string.IsNullOrEmpty(dataItem.Caption) ? dataItem.ColumnName : dataItem.Caption;
                    chkBindingControl.Properties.DisplayValueChecked = "True";
                    chkBindingControl.Properties.DisplayValueGrayed = "Gray";
                    chkBindingControl.Properties.DisplayValueUnchecked = "False";
                    chkBindingControl.Properties.ValueChecked = "True";
                    chkBindingControl.Properties.ValueGrayed = "Gray";
                    chkBindingControl.Properties.ValueUnchecked = "False";
                }
            }
            else if (dataItem.DataType == typeof(DateTime))
            {
                if (!(control is cDateEdit))
                {
                    _liveForm.Controls.Remove(control);
                    _liveContainer.Remove(control);
                    cDateEdit dateTimeBindingControl = new cDateEdit();
                    _liveForm.Controls.Add(dateTimeBindingControl);
                    _liveContainer.Add(dateTimeBindingControl);

                    dateTimeBindingControl.BindLabel = GetControlBindLable(control);
                    dateTimeBindingControl.DataColumn = dataItem;//new DataItem(dataItem.ColumnName, dataItem.DataType, dataItem.Length, dataItem.LogicalParent, dataItem.Simple, dataItem.UseEditor, dataItem.Queryable, dataItem.OnlyInWhereClause, dataItem.Validate, dataItem.Reference, dataItem.EnumMethod, dataItem.Caption, dataItem.FormatOption, dataItem.Required, dataItem.Insertable, dataItem.Flags, dataItem.UpdateOption);
                    dateTimeBindingControl.Location = control.Location;
                    dateTimeBindingControl.DataBindings.Add(new Binding("EditValue", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                    dateTimeBindingControl.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
                    new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
                    dateTimeBindingControl.Properties.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                    dateTimeBindingControl.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                    dateTimeBindingControl.Properties.EditFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                    dateTimeBindingControl.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                    dateTimeBindingControl.Properties.Mask.EditMask = "yyyy-MM-dd HH:mm:ss";
                    dateTimeBindingControl.Properties.VistaTimeProperties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
                    new DevExpress.XtraEditors.Controls.EditorButton()});
                    // dateTimeBindingControl.Format = System.Windows.Forms.DateTimePickerFormat.Short;
                    dateTimeBindingControl.Size = new System.Drawing.Size(140, 21);
                    dateTimeBindingControl.Site.Name = "dt" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                }
                else
                {
                    cDateEdit dateTimeBindingControl = control as cDateEdit;
                    dateTimeBindingControl.DataColumn = dataItem;
                    dateTimeBindingControl.Properties.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                    dateTimeBindingControl.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                    dateTimeBindingControl.Properties.EditFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                    dateTimeBindingControl.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                    dateTimeBindingControl.Properties.Mask.EditMask = "yyyy-MM-dd HH:mm:ss";
                   
                }
            }
           // else if (dataItem.DataType == typeof(byte[]) && dataItem.IsImage)
            else if ( dataItem.IsImage)
            {
                if (!(control is cPictureEdit))
                {
                    cPictureEdit picBindingControl = new cPictureEdit();
                    _liveForm.Controls.Add(picBindingControl);
                    _liveContainer.Add(picBindingControl);
                    picBindingControl.BindLabel = GetControlBindLable(control);
                    picBindingControl.Properties.SizeMode = PictureSizeMode.Clip;
                    picBindingControl.Properties.ShowMenu = true;
                    picBindingControl.Properties.ShowScrollBars = true;
                    picBindingControl.Properties.ShowZoomSubMenu = DevExpress.Utils.DefaultBoolean.True;
                    picBindingControl.Column = dataItem.ColumnName;
                    picBindingControl.DataColumn = dataItem;
                    picBindingControl.DataBindings.Clear();
                    picBindingControl.DataBindings.Add(new System.Windows.Forms.Binding("EditValue", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                    picBindingControl.Location = control.Location;
                    picBindingControl.Size = new System.Drawing.Size(140, 140);
                    picBindingControl.Site.Name = "pic" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                    picBindingControl.BringToFront();
                }
            }
            else if (dataItem.IsRichEdit)
            {
                if (!(control is cRichEdit))
                {
                    cRichEdit blobEdit = new cRichEdit();
                    _liveForm.Controls.Add(blobEdit);

                    _liveContainer.Add(blobEdit);
                    blobEdit.ActiveViewType = DevExpress.XtraRichEdit.RichEditViewType.Simple;
                    blobEdit.BindLabel = GetControlBindLable(control);
                    blobEdit.Column = dataItem.ColumnName;
                    blobEdit.DataColumn = dataItem;
                    blobEdit.DataBindings.Clear();
                    blobEdit.DataBindings.Add(new System.Windows.Forms.Binding("OpenDocumentBytes", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                  //  blobEdit.DataBindings.Add(new System.Windows.Forms.Binding("Text", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                    blobEdit.Location = control.Location;
                    blobEdit.Size = new System.Drawing.Size(140, 200);
                    blobEdit.Site.Name = "blob" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                    blobEdit.BringToFront();
                }
            }
            else if (dataItem.IsBlobEdit)
            {
                if (!(control is cRichEdit))
                {
                    cBlobEdit blobEdit = new cBlobEdit();
                    _liveForm.Controls.Add(blobEdit);

                    _liveContainer.Add(blobEdit);

                    blobEdit.BindLabel = GetControlBindLable(control);
                    blobEdit.Column = dataItem.ColumnName;
                    blobEdit.DataColumn = dataItem;
                    blobEdit.DataBindings.Clear();
                    blobEdit.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
                    new DevExpress.XtraEditors.Controls.EditorButton()});
                    blobEdit.DataBindings.Add(new System.Windows.Forms.Binding("Text", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                    blobEdit.Location = control.Location;
                    blobEdit.Size = new System.Drawing.Size(140, 24);
                    blobEdit.Site.Name = "blob" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                    blobEdit.BringToFront();
                }
            }
            else
            {
                Control nameControl = null;
                if (dataItem.Flags == Platform.Enums.DataItemFlags.Key && dataItem.PropertyChanged == true)
                {
                    if (!(control is cRecSelComboBox))
                    {
                        _liveForm.Controls.Remove(control);
                        _liveContainer.Remove(control);

                        cRecSelComboBox rsBindingControl = new cRecSelComboBox();
                        _liveForm.Controls.Add(rsBindingControl);
                        _liveContainer.Add(rsBindingControl);
                       
                    
                        rsBindingControl.BindLabel = GetControlBindLable(control);
                        rsBindingControl.DataColumn = dataItem;
                        rsBindingControl.BackColor = System.Drawing.SystemColors.Control;
                        //rsBindingControl.ControlSize = new System.Drawing.Size(474, 257);
                        rsBindingControl.DataBindings.Add(new Binding("EditValue", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                        rsBindingControl.DataSource = oldDataSourceBinding;
                        rsBindingControl.DisplayMember = dataItem.ColumnName;
                        rsBindingControl.ValueMember = dataItem.ColumnName;
                        //rsBindingControl.DropSize = new System.Drawing.Size(133, 106);
                        rsBindingControl.Location = control.Location;
                        rsBindingControl.Size = new System.Drawing.Size(140, 21);
                       
                        nameControl = rsBindingControl;
                        rsBindingControl.Site.Name = "scb" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                    }
                    else
                    {
                        cRecSelComboBox rsBindingControl = control as cRecSelComboBox;
                        
                        rsBindingControl.DataColumn = dataItem;
                        rsBindingControl.BindLabel = GetControlBindLable(control);
                       
                        rsBindingControl.DataSource = oldDataSourceBinding;
                        rsBindingControl.Location = control.Location;
                        rsBindingControl.Size = new System.Drawing.Size(140, 21);
                       
                        rsBindingControl.DisplayMember = dataItem.ColumnName;
                        rsBindingControl.ValueMember = dataItem.ColumnName;
                        
                    }
                }
                else if (!string.IsNullOrEmpty(dataItem.EnumMethod))
                {
                    if (!(control is cComboBox))
                    {
                        _liveForm.Controls.Remove(control);
                        _liveContainer.Remove(control);

                        cComboBox cboBindingControl = new cComboBox();
                        cboBindingControl.DataColumn = dataItem;
                        _liveForm.Controls.Add(cboBindingControl);
                        _liveContainer.Add(cboBindingControl);
                        cboBindingControl.BindLabel = GetControlBindLable(control);
                        cboBindingControl.DataBindings.Add(new System.Windows.Forms.Binding("Text", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                        cboBindingControl.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
                        cboBindingControl.Properties.AutoComplete = true;
                        cboBindingControl.Location = control.Location;
                        cboBindingControl.Size = new System.Drawing.Size(140, 20);
                        cboBindingControl.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
                        new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
                        cboBindingControl.Site.Name = "cbo" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                        cboBindingControl.BringToFront();
                        nameControl = cboBindingControl;
                    }
                    else
                    {
                        cComboBox cboBindingControl = control as cComboBox;
                        cboBindingControl.DataColumn = dataItem;
                        
                        cboBindingControl.BindLabel = GetControlBindLable(control);
                        cboBindingControl.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
                        cboBindingControl.Properties.AutoComplete = true;
                        cboBindingControl.Location = control.Location;
                        cboBindingControl.Size = new System.Drawing.Size(140, 20);
                        cboBindingControl.Site.Name = "cbo" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                    }
                }
                else
                {
                    if (!(control is cTextEdit))
                    {
                        _liveForm.Controls.Remove(control);
                        _liveContainer.Remove(control);

                        cTextEdit txtBindingControl = new cTextEdit();
                        _liveForm.Controls.Add(txtBindingControl);
                        _liveContainer.Add(txtBindingControl);
                        txtBindingControl.BindLabel = GetControlBindLable(control);
                        txtBindingControl.DataColumn = dataItem;
                        txtBindingControl.DataBindings.Clear();
                        txtBindingControl.DataBindings.Add(new System.Windows.Forms.Binding("Text", oldDataSourceBinding, dataItem.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged));
                        txtBindingControl.Location = control.Location;
                        txtBindingControl.Size = new System.Drawing.Size(140, 21);
                        txtBindingControl.Site.Name = "txt" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);

                        nameControl = txtBindingControl;
                    }
                    else
                    {
                        ((cTextEdit)control).DataColumn = dataItem;
                    }
                }

                //if (dataItem.DataType == typeof(byte) ||
                //    dataItem.DataType == typeof(byte[]) ||
                //    dataItem.DataType == typeof(char) ||
                //    dataItem.DataType == typeof(Guid) ||
                //    dataItem.DataType == typeof(object) ||
                //    dataItem.DataType == typeof(sbyte) ||
                //    dataItem.DataType == typeof(string) ||
                //    dataItem.DataType == typeof(TimeSpan))
                //    nameControl.Site.Name = "dfs" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                //else if (dataItem.DataType == typeof(decimal) ||
                //    dataItem.DataType == typeof(double) ||
                //    dataItem.DataType == typeof(Int16) ||
                //    dataItem.DataType == typeof(int) ||
                //    dataItem.DataType == typeof(Int64) ||
                //    dataItem.DataType == typeof(Single) ||
                //    dataItem.DataType == typeof(UInt16) ||
                //    dataItem.DataType == typeof(uint) ||
                //    dataItem.DataType == typeof(UInt64))
                //{
                //    nameControl.Site.Name = "dfn" + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(dataItem.ColumnName);
                //    if (nameControl is cTextEdit)
                //        ((cTextEdit)nameControl).Properties.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
                //}
            }
        }
        private List<fnd_table_defined> Tables = new List<fnd_table_defined>();
        private static DAL _dal = null;
        private static DAL dal
        {
            get
            {
                if (_dal == null)
                {
                    //string filePath = System.IO.Directory.GetCurrentDirectory() + "\\App.config";
                    //if (!System.IO.File.Exists(filePath))
                    //{
                        frmLoginDb loginDb = new frmLoginDb();
                        if (loginDb.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            _dal = DAL.Create(loginDb.DbType);
                            _dal.Session.Open();
                            return _dal;
                        }
                        else
                            return null;
                    //}
                    //else
                    //{
                    //    AssemblyX.DevEn = true;
                    //    XmlDocument doc = new XmlDocument();
                    //    try
                    //    {
                    //        doc.Load(filePath);
                    //    }
                    //    catch (XmlException ex)
                    //    {
                    //        Console.WriteLine(ex.Message);
                    //        //throw;
                    //    }
                    //    XmlElement root = doc.DocumentElement;
                    //    if (root.ChildNodes != null && root.ChildNodes.Count > 0)
                    //    {
                    //        foreach (XmlNode item in root.ChildNodes)
                    //        {
                    //            if (item.Name != "connectionStrings")
                    //                continue;

                    //            if (item.ChildNodes != null && (item.ChildNodes.Count > 1))
                    //            {
                    //                foreach (XmlNode cItem in item.ChildNodes)
                    //                {
                    //                    if (cItem.Attributes == null)
                    //                        continue;
                    //                    string dbType = cItem.Attributes[0].Value;
                    //                    string connnectstring = cItem.Attributes[1].Value;
                    //                    string provider = cItem.Attributes[2].Value;
                    //                    Type dType = null;

                    //                    if (dbType.ToUpper() == "MYSQL")
                    //                        dType = typeof(Fcdbas.Core.DataAccess.MySql);
                    //                    else if (dbType.ToUpper() == "ORACLE")
                    //                        dType = typeof(Fcdbas.Core.DataAccess.Oracle);
                    //                    DAL.AddConnStr(dbType, connnectstring, dType, provider);
                    //                }
                    //            }

                    //        }
                    //    }
                    //    _dal = DAL.Create("MySql");
                    //    return _dal;
                    //}
                }
                else
                    return _dal;

            }
            set
            {
                _dal = value;
            }
        }
        private void btnScanView_Click(object sender, EventArgs e)
        {
            if (dal == null)
            {
                frmLoginDb loginDb = new frmLoginDb();
                if (loginDb.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    dal = DAL.Create(loginDb.DbType);
                    dal.Session.Open();
                }
            }
            DataSet ds = dal.Select("select * from fnd_table_defined");
            if (ds != null && ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    fnd_table_defined fdd = new fnd_table_defined();
                    foreach (DataColumn dc in ds.Tables[0].Columns)
                    {
                        fdd[dc.ColumnName] = dr[dc.ColumnName];
                    }

                    Tables.Add(fdd);
                    cboView.Properties.Items.Add(fdd.view_name.ToLower());
                }
            }
            //List<fnd_table_defined> tables= Entity<fnd_table_defined>.FindAll();
            //foreach (fnd_table_defined table in tables)
            //{
            //    cboView.Properties.Items.Add(table.view_name);
            //}
        }
        private Type GetTypeByDataType(string datatype)
        {
            switch (datatype.ToLower())
            {
                case "varchar":
                    return typeof(string);
                case "int":
                    return typeof(int);
                case "datetime":
                case "date":
                case "time":
                    return typeof(DateTime);
                case "decimal":
                    return typeof(decimal);
                case "text":
                    return typeof(string);
                case "blob":
                    return typeof(byte[]);

            }
            return typeof(string);
        }
        private Platform.Enums.DataItemFlags GetFlag(string flag)
        {
            switch (flag)
            {
                case "K":
                    return Platform.Enums.DataItemFlags.Key;
                case "P":
                    return Platform.Enums.DataItemFlags.ParentKey;
                case "A":
                    return Platform.Enums.DataItemFlags.Attribute;
            }
            return Platform.Enums.DataItemFlags.Attribute;
        }
        private Platform.Enums.DataItemUpdate GetUpdate(string update)
        {
            switch (update)
            {
                case "U":
                    return Platform.Enums.DataItemUpdate.Allow;
                case "N":
                    return Platform.Enums.DataItemUpdate.AllowedIfNull;
                default:
                    return Platform.Enums.DataItemUpdate.NotAllowed;
            }

        }
        private List<DataItem> TableColumns = new List<DataItem>();
        private void btnScanColumn_Click(object sender, EventArgs e)
        {
            
        }
        private string GetControlName(string columnName,bool addDSName=true)
        {
            if (string.IsNullOrEmpty(columnName))
                return columnName;

            string name = columnName.Substring(0, 1).ToUpper() + columnName.Remove(0, 1);
            int idx = name.IndexOf("_");
            if (idx > 0 && idx < name.Length - 2)
            {
                string s = name.Substring(idx + 1, 1).ToUpper();
                string s1 = name.Substring(0, idx);
                string s2 = name.Substring(idx + 2, name.Length - idx - 2);
                if (addDSName)
                    return this.oldDataSource.Name + s1 + s + s2;
                else
                    return s1 + s + s2;
            }
            else
            {
                if (addDSName)
                    return this.oldDataSource.Name + name;
                else
                    return name;
            }
        }
        private void btnAddItem_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cboView.Text))
            {
                XtraMessageBox.Show("请选择要扫描的视图！");
                return;
            }
            if (dal == null)
            {
                frmLoginDb loginDb = new frmLoginDb();
                if (loginDb.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    dal = DAL.Create(loginDb.DbType);
                    dal.Session.Open();
                }
            }
            //if (TableColumns == null || TableColumns.Count <= 0)
            //{
                DataSet ds = dal.Select("select * from fnd_column_defined where lcase(view_name)='" + cboView.Text.ToLower() + "' order by column_index");
                if (ds != null && ds.Tables.Count > 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        if (dr["column_name"].ToString().ToLower() == "objid")
                            continue;
                        if (dr["column_name"].ToString().ToLower() == "objversion")
                            continue;

                        DataItem di = new DataItem()
                        {
                            Name = dr["column_name"].ToString(),
                            ColumnName = dr["column_name"].ToString().ToLower(),
                            Length = dr["data_length"] == null ? 0 : string.IsNullOrEmpty(dr["data_length"].ToString()) ? 0 : int.Parse(dr["data_length"].ToString()),
                            DataType = GetTypeByDataType(dr["data_type"].ToString()),
                            Caption = dr["prompt_text"].ToString(),
                            Flags = GetFlag(dr["type_flag"] == null ? "A" : dr["type_flag"].ToString()),
                            FormatOption = dr["data_format"] == null ? "A" : dr["data_format"].ToString(),
                            Required = dr["required_flag"].ToString() == "M" ? true : false,
                            Insertable = dr["insert_flag"].ToString() == "I" ? true : false,
                            UpdateOption = GetUpdate(dr["update_flag"].ToString()),
                            Reference = dr["col_reference"] == null ? "" : dr["col_reference"].ToString(),
                            EnumMethod = dr["enumeration"] == null ? "" : dr["enumeration"].ToString(),
                            OnlyInWhereClause = true
                        };
                        DataItem d = TableColumns.Find(p => p.ColumnName == di.ColumnName);
                        if (d == null)
                            TableColumns.Add(di);
                    }
                }

                for (int i = 1; i <= 10; i++ )
                {

                    string column = "Reference";
                    DataItem di = new DataItem()
                    {
                        Name = column + i.ToString(),
                        ColumnName = column + i.ToString(),
                        Length = 128,
                        DataType = typeof(string),
                        Caption = column + i.ToString(),
                        Flags = DataItemFlags.Attribute,
                        FormatOption = "Unformatted",
                        Required =  false,
                        Insertable = false,
                        AddToForm = false,
                        Queryable = false,
                        UpdateOption = DataItemUpdate.NotAllowed,
                        Reference = "",
                        EnumMethod = "",
                        OnlyInWhereClause = true
                    };
                    DataItem d = TableColumns.Find(p => p.ColumnName == di.ColumnName);
                    if (d == null)
                        TableColumns.Add(di);
                }
            //}
            //if (TableColumns.Count <= 0)
            //{
            //    XtraMessageBox.Show("请先扫描字段信息！");
            //    return;
            //}

            DataItemPropertiesEdit itemEdit = new DataItemPropertiesEdit(TableColumns,this.oldDataSource); 
            if (itemEdit.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                if (itemEdit.IsSingle)
                {
                    if (itemEdit.CurrentDataItem != null)
                    {
                        if (dataColumns.Find(p => p.ColumnName == itemEdit.CurrentDataItem.ColumnName) == null)
                            dataColumns.Add(itemEdit.CurrentDataItem);
                    }
                }
                else
                {
                    foreach (DataItem di in itemEdit.SelectItems)
                    {
                        if (dataColumns.Find(p => p.ColumnName == di.ColumnName) == null)
                            dataColumns.Add(di);
                    }
                }
            }
            //ndingSource1.DataSource = dataColumns;
            gcColumns.DataSource = dataColumns;
            gcColumns.RefreshDataSource();
            InitGridSelectItem();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            Map(false);
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        private void btnRemoveItem_Click(object sender, EventArgs e)
        {
            if (gvColumns.GetFocusedRow() != null)
            {
                DataItem di = gvColumns.GetFocusedRow() as DataItem;
                this.dataColumns.Remove(di);
                this.gcColumns.RefreshDataSource();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }
    }
}